/*
 * @Author: your name
 * @Date: 2020-12-30 15:37:17
 * @LastEditTime: 2021-01-08 15:04:57
 * @LastEditors: Please set LastEditors
 * @Description:操作数据库
 * @FilePath: \node-server\service\user.js
 */

const { querySql } = require('../db')
/**
 * @description: 获取用户信息
 * @param {*} username
 * @return {*}
 */
const getUserInfoDao = async (username) => {
   const sql = `select username,id,create_time from users where username='${username}'`
   return await querySql(sql)
}
/**
 * @description: 登录逻辑校验
 * @param {string} username
 * @param {string} password
 * @return {*}
 */
const checkLoginDao = async (username, password) => {
    let userIsRegister = true //用户是否注册
    const sql = `select password from users where username='${username}'`
    const {results} = await querySql(sql)
    if (results.length) {
        if (results[0].password == password) {
            return {
                status: 1,
                userIsRegister,
            }
        } else {
            return {
                status: 0,
                userIsRegister,
            }
        }
    } else {
        userIsRegister = false
        return {
            status: 0,
            userIsRegister,
        }
    }
}
/**
 * @description: 用户注册
 * @param {string} username
 * @param {string} password
 * @return {*}
 */
const registerDao = async (username, password, create_time) => {
    const { status } = await userIsExist(username)
    if (status) {
        const sql = `insert into users (username, password , create_time) values ('${username}', '${password}' , '${create_time}')`
        return querySql(sql)
    } else {
        return status
    }

}
// 查询用户是否存在
const userIsExist = async (username) => {
    const sql = `select * from users where username='${username}'`
    const {results} = await querySql(sql)
    if (results.length) {
        return {
            status: 0,
            msg: '用户已存在'
        }
    } else {
        return {
            status: 1,
            msg: '用户未注册'
        }
    }
}
module.exports = {
    checkLoginDao,
    registerDao,
    userIsExist,
    getUserInfoDao
}